﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using DrillOnline.Models;
using DrillOnline.Services.Scenarios;

namespace DrillOnline.Services
{
    public class MyViewPageBase : MyViewPageBase<dynamic> { }
    public class MyViewPageBase<T> : System.Web.Mvc.WebViewPage<T>
    {
        public Guid UserTenantId
        {
            get
            {
                return Guid.Parse("5db514e1-69ee-4b26-bffe-354b64e709f9");
            }
        }

        public IPrincipal SiteUser
        {
            get
            {
                return User;
            }
        }
        public Services.Scenarios.Actor ScenariosUser
        {
            get
            {
                var cs = GetCurrentSession();
                var ur=GetUserRole();
                if (ur=="Actor")
                {
                    var a = cs.ActorGroups.Where(v=>v.Actors!=null) .SelectMany(v => v.Actors).FirstOrDefault(v => v.ActorKey == SiteUser.Identity.Name);
                    return a;
                }
                else if (ur=="Examiner")
                {
                    var a = cs.ActorGroups.Where(v=>v.Examiners!=null).SelectMany(v =>  v.Examiners).FirstOrDefault(v => v.ActorKey == SiteUser.Identity.Name);
                    return a;
                }
                return null;
            }
        }


        public DrillScenarios GetCurrentSession()
        {
            if (!ScenariosHost.Instance.Sessions.ContainsKey("default"))
            {
                return null;
            }
            else
            {
                return ScenariosHost.Instance.Sessions["default"] as DrillScenarios;
            }
        }


        public override void Execute()
        {
            ;
        }

        public DrillScenarios ThisSession
        {
            get
            {
                if (!ScenariosHost.Instance.Sessions.ContainsKey("default"))
                {
                    return null;
                }
                else
                {
                    return ScenariosHost.Instance.Sessions["default"] as DrillScenarios;
                }
            }
        }


        public string GetUserRole()
        {
            if (!SiteUser.Identity.IsAuthenticated) return "Guest";
            if (SiteUser.Identity.Name == "管理员") return "Manager";
            var cs = GetCurrentSession();
            if (cs == null ) return "Guest";

            if (cs.ActorGroups.Any(v => v.Examiners!=null && v.Examiners.Any(j => j.ActorKey == SiteUser.Identity.Name))) return "Examiner";

            if (cs.ActorGroups.Any(v => v.Actors!=null && v.Actors.Any(j => j.ActorKey == SiteUser.Identity.Name))) return "Actor";
            return "Guest";
        }
    }
}